/*
 * 創建期日 2005-5-10
 */
package com.taylor.core.db;

import java.sql.Connection;
import java.sql.SQLException;



/**
 * <p>
 * Title: Livedorr
 * </p>
 * <p>
 * Description: Taylor
 * </p>
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * <p>
 * Company: 英極軟件開發（大連）有限公司
 * </p>
 * 
 * @author 凌です
 * @version 1.0
 */

public class DBSession {
	private static final ThreadLocal session = new ThreadLocal();

	private DBSession() {
	}

	public static void openSession(boolean isBeginTransaction)
		throws DBException {

		Connection conn = (Connection) session.get();
		if (conn != null) {
			throw new DBException("Session already opened.");
		}

		Connection _conn = DataSourceSingleton.getInstance().getConnection();
		try {
			_conn.setAutoCommit(!isBeginTransaction);
		} catch (SQLException sqle) {
			throw new DBException("Session set auto commit failure.", sqle);
		}

		conn = _conn;
		session.set(conn);
	}

	public static void commitTransaction() throws DBException {
		Connection conn = currentConnection();
		try {
			conn.commit();
		} catch (SQLException sqle) {
			throw new DBException(
				"Session set commit transaction failure.",
				sqle);
		}

	}

	public static void rollbackTransaction() throws DBException {
		Connection conn = currentConnection();
		try {
			conn.rollback();
		} catch (SQLException sqle) {
			throw new DBException(
				"Session set rollback transaction failure.",
				sqle);
		}
	}

	public static void closeSession() throws DBException {
		Connection conn = currentConnection();
		try {
			conn.close(); 
		} catch (SQLException sqle) {
			throw new DBException("Session close failure.", sqle);
		}
		conn = null;
		session.set(null);
	}

	public static Connection currentConnection() throws DBException {
		Connection conn = (Connection) session.get();
		if (conn == null) {
			throw new DBException("Session not open.");
		}

		return conn;
	}
    
    public static boolean isSessionOpened() throws DBException {
        return session.get()!=null;
    }

}